import axios from "axios";
import { ElLoading, ElMessage } from "element-plus";

let loading;
const startLoading = () => {
  const options = {
    lock: true,
    text: "拼命加载中...",
    background: "rgba(255,255,255,.7)",
  };
  loading = ElLoading.service(options);
};
const endLoading = () => {
  loading.close();
};

const service = axios.create({
  baseURL:
    process.env.NODE_ENV === "development"
      ? "/apis"
      : process.env.VUE_APP_AUTH_API_DOMAIN, // url = base url + request url
  // baseURL: `http://192.168.1.239:8081`,
  // baseURL: `https://yapi.doc.nterp.nantang-tech.com/mock/17`,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 500000, // request timeout
});
// 请求拦截
service.interceptors.request.use((config) => {
  startLoading();
  config.headers.Authorization = localStorage.token;

  return config;
});

// 响应拦截

service.interceptors.response.use(
  (response) => {
    endLoading();
    let { code, msg } = response.data;
    if (code !== 0) {
      // code等于直接弹出msg显示
      if (code === 1) {
        ElMessage({
          message: msg || "请求错误",
          type: "error",
        });
      }
    } else {
      return response.data;
    }
  },
  (error) => {
    //错误处理
    endLoading();
    return Promise.reject(error);
  }
);

export default service;
